package com.company.workflow.loader;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.opensymphony.workflow.InvalidWorkflowDescriptorException;
import com.opensymphony.workflow.loader.AbstractDescriptor;
import com.opensymphony.workflow.loader.ValidationHelper;
import com.opensymphony.workflow.util.Validatable;
import com.opensymphony.workflow.util.XMLizable;

public class ConditionsDescriptor extends AbstractDescriptor implements
		Validatable {
	// ~ Instance fields
	// ////////////////////////////////////////////////////////

	private List conditions = new ArrayList();

	private String type;

	ConditionDescriptor d;

	// ~ Constructors
	// ///////////////////////////////////////////////////////////

	public ConditionsDescriptor() {
	}

	public ConditionsDescriptor(Element element) {
		type = element.getAttribute("type");

		NodeList children = element.getChildNodes();
		int size = children.getLength();

		for (int i = 0; i < size; i++) {
			Node child = children.item(i);

			if (child instanceof Element) {
				if ("condition".equals(child.getNodeName())) {
					ConditionDescriptor condition = new ConditionDescriptor(
							(Element) child);
					conditions.add(condition);
				} else if ("conditions".equals(child.getNodeName())) {
					ConditionsDescriptor condition = new ConditionsDescriptor(
							(Element) child);
					conditions.add(condition);
				}
			}
		}
	}

	// ~ Methods
	// ////////////////////////////////////////////////////////////////

	public void setConditions(List conditions) {
		this.conditions = conditions;
	}

	public List getConditions() {
		return conditions;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getType() {
		return type;
	}

	public void validate() throws InvalidWorkflowDescriptorException {
		ValidationHelper.validate(conditions);

		if ((conditions.size() > 1) && (type == null)) {
			throw new InvalidWorkflowDescriptorException(
					"Conditions must have AND or OR type specified");
		}
	}

	public String getXML() {
		StringBuffer sb = new StringBuffer();

		if (conditions.size() > 0) {

			sb.append("<conditions");
			if (conditions.size() > 1) {
				sb.append(" type=\"").append(type).append("\"");
			}

			sb.append(">");

			for (int i = 0; i < conditions.size(); i++) {
				ConditionDescriptor condition = (ConditionDescriptor) conditions
						.get(i);
				sb.append(condition.getXML());
			}

			sb.append("</conditions>");
		}
		return sb.toString();
	}

	public void writeXML(PrintWriter writer, int indent) {
		// TODO Auto-generated method stub

	}
}
